<script setup lang="ts">
const props = defineProps<{
  visible: boolean;
  targetEl?: HTMLElement | null;
}>();

const emit = defineEmits(["update:visible", "rename", "delete"]);

const popupRef = ref<HTMLDivElement | null>(null);
const popupStyle = ref({});

// 计算并更新弹窗位置
const updatePosition = () => {
  if (!props.targetEl) return;
  const rect = props.targetEl.getBoundingClientRect();
  popupStyle.value = {
    top: `${rect.bottom + window.scrollY + 15}px`,
    left: `${rect.left + window.scrollX}px`,
  };
};

// 点击外部关闭
const handleClickOutside = (e: MouseEvent) => {
  if (popupRef.value && !popupRef.value.contains(e.target as Node)) {
    closePopup();
  }
};
const closePopup = () => emit("update:visible", false);
const handleButtonClick = (action: "rename" | "delete") => {
  emit(action);
  closePopup();
};
watch(
  () => props.visible,
  (val) => {
    if (val) {
      updatePosition();
      document.addEventListener("click", handleClickOutside);
    } else {
      document.removeEventListener("click", handleClickOutside);
    }
  }
);

onMounted(() => {
  if (props.visible) {
    document.addEventListener("click", handleClickOutside);
  }
});

onBeforeUnmount(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>

<template>
  <Teleport to="body">
    <transition name="popconfirm-fade">
      <div
        v-if="visible"
        ref="popupRef"
        class="cus_popconfirm"
        :style="popupStyle"
      >
        <div class="rename_div" @click.stop="handleButtonClick('rename')">
          <SvgIcon name="rewrite" height="20px" width="20px" />
          <div class="rename_text">重命名</div>
        </div>
        <div class="delete_div" @click.stop="handleButtonClick('delete')">
          <SvgIcon name="delete" height="20px" width="20px" />
          <div class="delete_text">删除</div>
        </div>
      </div>
    </transition>
  </Teleport>
</template>

<style scoped lang="scss">
.popconfirm-fade-enter-active,
.popconfirm-fade-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

.popconfirm-fade-enter-from,
.popconfirm-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
@mixin menu-item-base {
  width: 100%;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  cursor: pointer;
  border-radius: 10px;
  padding: 0 10px;
  box-sizing: border-box;
  transition: all 0.3s;
  .rename_text,
  .delete_text {
    font-size: 15px;
    margin-left: 9px;
  }
}
.cus_popconfirm {
  position: fixed;
  z-index: 1000;
  width: 102px;
  height: 84px;
  border-radius: 10px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  box-sizing: border-box;
  padding: 4px;
  background-color: #fff;
  .rename_div {
    @include menu-item-base;
    color: #404040;
    &:hover {
      background-color: #f5f5f5;
    }
  }
  .delete_div {
    @include menu-item-base;
    color: #ef4444;
    &:hover {
      background-color: #fef4f4;
    }
  }
}
</style>
